package id.co.shuba.spamobile.activities;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.util.Base64;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;

public class SplashActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spash);
        
        TextView txt = (TextView) findViewById(R.id.txtVersion);
        txt.setText("Version " + App.getAppVersion(this));
        
        try {
			prepareDirectory();
		} catch (IOException e1) {		
			e1.printStackTrace();
		}
        
        Thread sub = new Thread(new Runnable() {			
			public void run() {				
				try {
					Thread.sleep(1000);
					//Thread.sleep(3000);
				} catch (InterruptedException e) {					
					e.printStackTrace();
				} finally {
					Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
					startActivity(intent);
					finish();
				}
			}
		});
        
        sub.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_spash, menu);
        return true;
    }    
    
    private void prepareDirectory() throws IOException {
    	File sdPat = Environment.getExternalStorageDirectory();
		File spamobile = new File(sdPat, "spamobile");
		if (!spamobile.exists()) {
			spamobile.mkdir();			
		}
		File spamobileExport = new File (spamobile, "export");
		if (!spamobileExport.exists()) {
			spamobileExport.mkdir();
		}
		File spamobileImport = new File (spamobile, "import");
		if (!spamobileImport.exists()) {
			spamobileImport.mkdir();
		}		
		
		File version = new File(spamobile, "version");
		if (version.exists()) {
			version.delete();
		}
		
		version.createNewFile();
		FileWriter writer = new FileWriter(version);
		BufferedWriter buff = new BufferedWriter(writer);
		buff.write(Base64.encodeBytes(App.getAppVersion(this).getBytes()));
		buff.close();
		writer.close();
    }
}
